﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;

namespace psy_service.fwpt
{
    public static class fwpt
    {
        public static string nsrsbh = string.Empty;
        public static string sessionId = string.Empty;
        public static string psyurl = string.Empty;
        private static void Runlogout(string text)
        {
            Console.WriteLine(text);
        }

        //获取税号
        public static string getNsrsbh(HttpListenerRequest request, HttpListenerResponse response)
        {
            string sh = request.QueryString["nsrsbh"];
            string Id = request.QueryString["sessionId"];
            string ip = "http://gd.kaipiaoba.cn/bwkp/fp/"+ sh + "/";//request.QueryString["url"];
            string decode = HttpUtility.UrlDecode(ip, Encoding.UTF8);

            Runlogout("用户登录：" + request.Url.PathAndQuery);
            if (Id.Length != 0)
            {
                sessionId = Id;
                nsrsbh = sh;
                psyurl = decode + "/api/";
                return "{\"code\":0,\"msg\":\"成功\"}";
            }
            return "{\"code\":-1,\"msg\":\"非法参数\"}";
        }

        //验证证书口令
        public static string verifyPin(HttpListenerRequest request, HttpListenerResponse response)
        {
            if (psyurl.Length <= 0)
            {
                return "{\"code\":999001,\"msg\":\"票税云综合服务：未通过票税云登录\"}";
            }

            Runlogout("接收请求：" + request.Url.PathAndQuery);

            //获取Post数据
            Stream stream = request.InputStream;
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);

            NameValueCollection QueryString = GetQueryString(reader.ReadToEnd());
            if (QueryString["strContainer"] == null)
            {
               return "{\"code\":999034,\"msg\":\"票税云综合服务：获取证书失败\"}";
            }
            string password = QueryString["password"];
            string dwProvType = QueryString["dwProvType"];
            string postData = string.Format("password={0}&dwProvType={1}", password, dwProvType);
            string VerifyJson = sendPost(psyurl + "verifyPin", postData, sessionId);
            return VerifyJson;
        }

        //获取证书信息
        public static string readCertInfo(HttpListenerRequest request, HttpListenerResponse responsep)
        {
            Runlogout("接收请求：" + request.Url.PathAndQuery);
            if (nsrsbh.Length > 0)
            {
                return "{\"code\":0,\"msg\":\"获取证书成功\",\"certInfo\":\"" + nsrsbh + "\"}";
            }
            return "{\"code\":999001,\"msg\":\"票税云综合服务：未通过票税云登录\"}";
        }

        //客户端hello
        public static string clientHello(HttpListenerRequest request, HttpListenerResponse responsep)
        {
            Runlogout("接收请求：" + request.Url.PathAndQuery);
            //获取Post数据
            Stream stream = request.InputStream;
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string queryString = reader.ReadToEnd();
            NameValueCollection QueryString = GetQueryString(queryString);

            string authType = QueryString["authType"];
            string dwProvType = QueryString["dwProvType"];
            string postData = string.Format("authType={0}&dwProvType={1}", authType, dwProvType);
            string clientHello = sendPost(psyurl + "clientHello", postData, sessionId);

            if(!JsonSplit.IsJson(clientHello))
            {
                return "{\"code\":999006,\"msg\":\"票税云综合服务：" + clientHello + "\"}";
            }
            return clientHello;
        }

        //客户端验证
        public static string clientAuth(HttpListenerRequest request, HttpListenerResponse responsep)
        {
            Runlogout("接收请求：" + request.Url.PathAndQuery);

            //获取Post数据
            Stream stream = request.InputStream;
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string queryString = reader.ReadToEnd();
            NameValueCollection QueryString = GetQueryString(queryString);

            string password = QueryString["password"];
            string serverHello = QueryString["serverHello"];
            string dwProvType = QueryString["dwProvType"];
            string postData = string.Format("password={0}&serverHello={1}&&dwProvType={2}", password, serverHello, dwProvType);
            string clientAuth = sendPost(psyurl + "clientAuth", postData, sessionId);
            new Thread(() => {
                Thread.Sleep(1000 * 60);
                nsrsbh = string.Empty;
                sessionId = string.Empty;
                psyurl = string.Empty;
            }).Start();
            return clientAuth;
        }

        //获取客户端版本
        public static string getVersion(HttpListenerRequest request)
        {
            Runlogout("接收请求：" + request.Url.PathAndQuery);
            return "{\"code\":0,\"msg\":\"获取版本号成功\",\"version\":\"1.0\"}";
        }

        //发送Post数据
        private static string sendPost(string url, string postdata, string sessionId)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 1000*5;
                request.Method = "POST";
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                request.Headers.Add("Cookie", string.Format("JSESSIONID={0};jeesite.session.id={0}", sessionId));
                request.AllowAutoRedirect = false;
                request.KeepAlive = true;
                byte[] postdatabyte = Encoding.GetEncoding("utf-8").GetBytes(postdata);
                request.ContentLength = postdatabyte.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(postdatabyte, 0, postdatabyte.Length);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                string strWebData = string.Empty;
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    strWebData = reader.ReadToEnd();
                }
                if(strWebData.Length <= 0)
                {
                    return "{\"code\":999004,\"msg\":\"票税云综合服务：服务器返回为空\"}";
                }
                Console.WriteLine(strWebData);
                return strWebData;
            }
            catch (WebException)
            {
                return "{\"code\":999005,\"msg\":\"票税云综合服务：访问服务器超时\"}";
            }
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString)
        {
            return GetQueryString(queryString, null, true);
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="encoding"></param>
        /// <param name="isEncoded"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
        {
            queryString = queryString.Replace("?", "");
            NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }
                    if (isEncoded)
                    {
                        result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
                    }
                    else
                    {
                        result[key] = value;
                    }
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 解码URL
        /// </summary>
        /// <param name="encoding">null为自动选择编码</param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                     
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }
    }
}
